package com.bascker.algorithm.practice;

import java.util.concurrent.atomic.AtomicBoolean;

public class Solution {

    private static final AtomicBoolean lock = new AtomicBoolean(true);

    private static final char[] letter = new char[] {
            'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r',
            's', 't', 'u', 'v', 'w', 'x',
            'y', 'z'
    };

    private static int index = 0;

    public static void main(String[] args) {
        Thread th1 = new Thread(new Runnable() {
            @Override
            public void run() {
                if (index % 3 != 0) {
                    return;
                }

                lock.compareAndSet(true, false);
                System.out.println(Thread.currentThread().getName() + "->" + letter[index]);
                lock.compareAndSet(false, true);
            }
        }, "线程1");

        Thread th2 = new Thread(new Runnable() {
            @Override
            public void run() {
                if (index % 3 != 1) {
                    return;
                }

                lock.compareAndSet(true, false);
                System.out.println(Thread.currentThread().getName() + "->" + letter[index]);
                lock.compareAndSet(false, true);
            }
        }, "线程2");

        Thread th3 = new Thread(new Runnable() {
            @Override
            public void run() {
                if (index % 3 != 2) {
                    return;
                }

                lock.compareAndSet(true, false);
                System.out.println(Thread.currentThread().getName() + "->" + letter[index]);
                lock.compareAndSet(false, true);
            }
        }, "线程3");

        for (int i = 0; i < letter.length; i ++) {
            if (lock.get()) {
                th1.start();
            }

            if (lock.get()) {
                th2.start();
            }

            if (lock.get()) {
                th3.start();
            }
        }
    }

}
